<template>
  <el-dialog
    title="权限配置"
    :visible.sync="dialogValue"
    width="500px"
    append-to-body
  >
    <el-tree
      v-if="dialogValue"
      ref="permissionTree"
      :data="permissionList"
      check-strictly
      show-checkbox
      :default-expanded-keys="checkedKeys"
      :default-checked-keys="checkedKeys"
      node-key="id"
      :props="defaultProps"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="onPageBack">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { http } from '@/api'
import { constantRoutes } from '@/router'

export default {
  name: 'FormAdd',
  data() {
    return {
      dialogValue: false,
      ruleForm: {
      },
      rules: {
      },

      permissionList: [
      ],
      checkedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created() {
    let data = []
    data = constantRoutes.filter(e => !e.hidden).map(el => {
      if (el.children && el.children.length === 1) {
        return {
          id: el.children[0].name,
          label: el.children[0].meta.title
        }
      } else {
        return {
          id: el.name,
          label: el.meta.title,
          children: (el.children || []).filter(e => !e.hidden).map(el2 => {
            return {
              id: el2.name,
              label: el2.meta.title
            }
          })
        }
      }
    })
    this.permissionList = data
  },
  methods: {
    async open(item) {
      this.ruleForm = item
      http.permission.read(item.id).then(res => {
        let list = []
        res.data.forEach(el => {
          list.push(el.code)
          el.menuList.forEach(el2 => {
            list.push(el2.code)
          })
        })
        list = list.filter(e => e)
        this.checkedKeys = [...list]
        this.dialogValue = true
      })
    },
    onPageBack() {
      this.$emit('get-page')
      this.dialogValue = false
    },
    onSave() {
      http.permission.update({
        userId: this.ruleForm.id,
        powers: this.$refs.permissionTree.getCheckedKeys()
      }).then(res => {
        this.$message.success(res.msg)
        this.onPageBack()
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
